# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base
class Collection(Base):

    @view_config(route_name='AppCollectionUploadRoute', request_method='POST')
    def AppCollectionUploadRoute(self):
        tel, tString, eString, tokenString, csc, data = '', '', '', '', '', ''
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            data = postParams.getone('data')
        except Exception, e:
            log.error(e)

        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)

        #map = {'RetCode':'0', 'message':'成功', 'data':resultSelect}
        #jsonStr = json.dumps(map, ensure_ascii=False)
        #dataArray = json.loads(dataJson, encoding="utf-8")
        dataArray = data.split('|')
        returnList = []
        for md5 in dataArray:
            log.debug('[MD5]' + md5)
            if UploadTasks.uploadCollectionByQueue(md5, tel, '2') >= 0:
                returnList.append(md5)
                log.debug('[UPLOADCOLLECTION][IMG]{' + md5 + '}[SUCCEED]')
        if len(dataArray) == len(returnList):
            map = {'RetCode': '0', 'message':'上传成功！', 'data':returnList, 'total':len(returnList)}
        elif len(returnList) == 0:
            map = {'RetCode': '142', 'message':'上传部分失败！', 'data':returnList, 'total':len(returnList)}
        else:
            map = {'RetCode': '142', 'message':'上传全部失败！', 'data':returnList, 'total':len(returnList)}
        jsonStr = json.dumps(map, ensure_ascii=False)
        log.debug(jsonStr)
        return Response(jsonStr)

    @view_config(route_name='AppCollectionRemoveRoute', request_method='POST')
    def AppCollectionRemoveRoute(self):
        tel, tString, eString, tokenString, csc, data = '', '', '', '', '', ''
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            data = postParams.getone('data')
        except Exception, e:
            log.error(e)

        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '145', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)

        dataArray = data.split('|')
        returnList = []
        for md5 in dataArray:
            log.debug('[MD5]' + md5)
            if UploadTasks.removeCollectionByQueue(md5, tel, '2') >= 0:
                returnList.append(md5)
                log.debug('[REMOVECOLLECTION][IMG]{' + md5 + '}[SUCCEED]')
        if len(dataArray) == len(returnList):
            map = {'RetCode': '0', 'message':'上传成功！', 'data':returnList, 'total':len(returnList)}
        elif len(returnList) == 0:
            map = {'RetCode': '142', 'message':'取消收藏部分失败！', 'data':returnList, 'total':len(returnList)}
        else:
            map = {'RetCode': '142', 'message':'取消收藏全部失败！', 'data':returnList, 'total':len(returnList)}
        jsonStr = json.dumps(map, ensure_ascii=False)
        log.debug(jsonStr)
        return Response(jsonStr)
